﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
//using Windows.Web.Http;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上有介绍

namespace LikeBangumi.Pages
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class FCPage : Page
    {
        public delegate void PageChnage(BangumiType type, string sid);
        public event PageChnage PageChnageEvent;
        public FCPage()
        {
            this.InitializeComponent();
         
            NavigationCacheMode = NavigationCacheMode.Required;
            TypeLoad();
        }
        private void TypeLoad()
        {
            List<CbTypeModel> list_Type = new List<CbTypeModel>() {
                new CbTypeModel() {Name="日本动漫",Info="http://m.fengchedm.com/list/138-{0}.html"},
                 new CbTypeModel() {Name="国产动漫",Info="http://m.fengchedm.com/list/137-{0}.html"},
                  new CbTypeModel() {Name="欧美动漫",Info="http://m.fengchedm.com/list/139-{0}.html"},
                   new CbTypeModel() {Name="韩国动漫",Info="http://m.fengchedm.com/list/140-{0}.html"},
                    new CbTypeModel() {Name="其他动漫",Info="http://m.fengchedm.com/list/157-{0}.html"},
            };
            cb_Type.ItemsSource = list_Type;
            cb_Type.SelectedIndex = 0;
        }
        private void btn_Home_Click(object sender, RoutedEventArgs e)
        {
            //(sender as Button).BorderBrush = new SolidColorBrush(new Windows.UI.Color() { A=255,B=216,G=123,R=30});
            if (Convert.ToInt32((sender as Button).Tag) == pivot.SelectedIndex)
            {
                switch (Convert.ToInt32((sender as Button).Tag))
                {
                    case 0:
                        GetNew();
                        break;
                    case 1:
                        //TypeLoad();
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            }
            else
            {
                pivot.SelectedIndex = Convert.ToInt32((sender as Button).Tag);
            }


        }

        private void UpdateUI()
        {
            SolidColorBrush color = new SolidColorBrush(new Windows.UI.Color() { A = 0, B = 0, G = 0, R = 0 });
            btn_Home.BorderBrush = color;
            btn_Seach.BorderBrush = color;
            btn_Tag.BorderBrush = color;
        }

        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UpdateUI();
            SolidColorBrush color = new SolidColorBrush(new Windows.UI.Color() { A = 255, B = 216, G = 123, R = 30 });
            switch (pivot.SelectedIndex)
            {
                case 0:
                    btn_Home.BorderBrush = color;
                    break;
                case 1:
                    btn_Tag.BorderBrush = color;
                    break;
                case 2:
                    btn_Seach.BorderBrush = color;
                    break;
                default:
                    break;
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode== NavigationMode.New)
            {
                if (list_Home.Items.Count==0)
                {
                    GetNew();
                }
            }
            
        }
        WebClientClass wc;
        private async void GetNew()
        {
            try
            {
                pr_Load.Visibility = Visibility.Visible;
                wc = new WebClientClass();
                string results = await wc.GetResults(new Uri("http://m.fengchedm.com/"));
                List<FCModel> list = new List<FCModel>();
                MatchCollection mc = Regex.Matches(results, @"<dt><a href=""(.*?)""><img src=""(.*?)"" /></a></dt>.*?<dd><a href="".*?"">(.*?)</a></dd>", RegexOptions.Singleline);
                foreach (Match item in mc)
                {
                    list.Add(new FCModel
                    {
                        url = "http://m.fengchedm.com" +item.Groups[1].Value,
                        img = item.Groups[2].Value,
                        title = item.Groups[3].Value
                    });
                }
                list_Home.ItemsSource = list;
                if (list.Count==0)
                {
                    messShow.Show("读取最近更新失败",3000);
                }
            }
            catch (Exception)
            {
                messShow.Show("读取最近更新错误", 3000);
            }
            finally
            {
                pr_Load.Visibility = Visibility.Collapsed;
            }
        }
        int PageNum = 1;
        private async Task GetTypeInfo()
        {
            try
            {
                InfoLoading = true;
                pr_Load.Visibility = Visibility.Visible; 
                wc = new WebClientClass();
                string results = string.Empty;
                results = await wc.GetResults(new Uri(string.Format((cb_Type.SelectedItem as CbTypeModel).Info, PageNum)));
                MatchCollection mc = Regex.Matches(results, @"<dt><a href=""(.*?)"">.*?<img src=""(.*?)"" /></a></dt>.*?<dd>.*?<a href="".*?"">(.*?)</a></dd>", RegexOptions.Singleline);
                foreach (Match item in mc)
                {
                    list_Type.Items.Add(new FCModel
                    {
                        url = "http://m.fengchedm.com" + item.Groups[1].Value,
                        img = item.Groups[2].Value,
                        title = item.Groups[3].Value
                    });
                }
                if (mc.Count==0)
                {
                    messShow.Show("没有数据", 3000);
                }
                PageNum++;
            }
            catch (Exception)
            {
                messShow.Show("加载失败",3000);
            }
            finally
            {
                pr_Load.Visibility = Visibility.Collapsed ;
                InfoLoading = false;
            }
           

        }
        int PageNum_Seach = 1;
        string SeaStr = string.Empty;
        private async Task GetSeachInfo()
        {
            try
            {
                InfoLoading_S = true;
                pr_Load.Visibility = Visibility.Visible;
                wc = new WebClientClass();
                //byte[] word = Encoding.GetEncoding("gb2312").GetBytes(SeaStr);
                //byte[] by = System.Net.WebUtility.UrlEncodeToBytes(word, 0, word.Length);
                string words = Uri.EscapeDataString(SeaStr);
                string url = string.Format("http://m.fengchedm.com/common/search.aspx?key={0}&pagesize={1}&pagenum={2}", words, PageNum_Seach,15); 
                string results = await wc.GetResults(new Uri(url));

               
                MatchCollection mc = Regex.Matches(results, @"<dt><a href=""(.*?)"">.*?<img src=""(.*?)"" /></a></dt>.*?<dd>.*?<a href="".*?"">(.*?)</a></dd>", RegexOptions.Singleline);
                foreach (Match item in mc)
                {
                    list_Seach.Items.Add(new FCModel
                    {
                        url = "http://m.fengchedm.com" + item.Groups[1].Value,
                        img = item.Groups[2].Value,
                        title = item.Groups[3].Value
                    });
                }
                if (mc.Count == 0)
                {
                    messShow.Show("没有数据", 3000);
                }
                PageNum_Seach++;
            }
            catch (Exception)
            {
                messShow.Show("加载失败", 3000);
            }
            finally
            {
                pr_Load.Visibility = Visibility.Collapsed;
                InfoLoading_S = false;
            }
        }
        private void list_Home_ItemClick(object sender, ItemClickEventArgs e)
        {
            PageChnageEvent(BangumiType.Fengche, (e.ClickedItem as FCModel).url);
        }

        private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            int i = Convert.ToInt32(this.ActualWidth / 100);
            ViewBox_num.Width = this.ActualWidth / i - 11;
        }

        private async void cb_Type_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            PageNum = 1;
            list_Type.Items.Clear();
            // (cb_Type.SelectedItem as CbTypeModel).Info
            await GetTypeInfo();
            await GetTypeInfo();
            await GetTypeInfo();

        }
        bool InfoLoading = false;
        private async void sv_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
        {
            if (sv.VerticalOffset == sv.ScrollableHeight)
            {
                if (!InfoLoading)
                {
                    await GetTypeInfo();
                }
            }
        }
        bool InfoLoading_S = false;
        private async void sv_Serch_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
        {
            if (sv_Serch.VerticalOffset == sv_Serch.ScrollableHeight)
            {
                if (!InfoLoading_S)
                {
                    await GetSeachInfo();
                }
            }
        }

        private async void seach_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
        {
            SeaStr = seach.Text;
            PageNum_Seach = 1;
            list_Seach.Items.Clear();
            await GetSeachInfo();
            await GetSeachInfo();
            await GetSeachInfo();
        }
    }
    public class FCModel
    {
        public string title { get; set; }
        public string img{ get; set; }
        public string url { get; set; }
    }

}
